import org.junit.Before;
import org.junit.Test;
import cn.jolyoulu.common.core.queue.delayed.DelayedTaskBootStrap;
import cn.jolyoulu.common.core.queue.delayed.DelayedTaskEntity;
import cn.jolyoulu.common.core.queue.delayed.DelayedTaskProducer;
import cn.jolyoulu.common.core.queue.delayed.observer.AbstractObserver;
import cn.jolyoulu.common.core.queue.delayed.observer.DelayedTaskSubject;

import java.time.LocalDateTime;
import java.util.concurrent.TimeUnit;

/**
 * @Author: JolyouLu
 * @Date: 2023/4/15 20:23
 * @Description
 */
public class DelayedTaskTest {

    private DelayedTaskProducer delayedTaskProducer;

    @Before
    public void before() {
        //构建一个生产者
        delayedTaskProducer = new DelayedTaskProducer();
        //观察者
        DelayedTaskSubject taskSubject = new DelayedTaskSubject();
        taskSubject.registerObserver(new StringObserver());
        taskSubject.registerObserver(new IntegerObserver());
        //构建延迟任务管理器
        new DelayedTaskBootStrap(1, delayedTaskProducer, taskSubject);
    }

    @Test
    public void test1() {
        delayedTaskProducer.put(new DelayedTaskEntity<>("11", LocalDateTime.now(),"测试任务"));
        delayedTaskProducer.put(new DelayedTaskEntity<>("11", LocalDateTime.now(),123456));
        //休眠1小时，等待观察者被触发
        try {
            TimeUnit.HOURS.sleep(1);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            throw new RuntimeException(e);
        }
    }

    private class StringObserver extends AbstractObserver<String> {

        public StringObserver() {
            super(String.class);
        }

        @Override
        protected void task(DelayedTaskEntity<String> delayedTask) {
            System.out.println(delayedTask.getTask());
        }
    }

    private class IntegerObserver extends AbstractObserver<Integer> {


        public IntegerObserver() {
            super(Integer.class);
        }

        @Override
        protected void task(DelayedTaskEntity<Integer> delayedTask) {
            System.out.println(delayedTask.getTask());
        }
    }
}
